package com.example.fasttalk.client;

import com.example.fasttalk.Constant;
import com.example.fasttalk.model.FastTalkGroupModel;
import com.example.fasttalk.model.FastTalkUserModel;
import com.example.fasttalk.model.intfc.FastTalkSettingData;
import com.example.fasttalk.tmodel.TTalkRecordInfo;
import com.google.gson.reflect.TypeToken;

import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.function.Consumer;

public class MessagesManagerClient {
  private static final MessagesManagerClient manage = new MessagesManagerClient();

  private FastTalkSettingData data;

  private FastTalkUserModel currentLoginUser;

  private List<Consumer<TTalkRecordInfo>> talkListenerList = new ArrayList<>();

  public void init(FastTalkSettingData data) {
    this.data = data;
    login();
    createServerTunnel();
  }

  private void createServerTunnel() {
    SseActuatorBuilder.builder()
      .serverUrl(data.getServerUrl())
      .api(ServerApiEnum.STREAM_SSE)
      .param(currentLoginUser.getUserName())
      .then(str -> {
        TTalkRecordInfo tTalkRecordInfo = Constant.GSON.fromJson(str, TTalkRecordInfo.class);
        talkListenerList.forEach(c -> c.accept(tTalkRecordInfo));
      }).execute();
  }

  private void login() {
    HttpActuatorBuilder.builder()
      .serverUrl(data.getServerUrl())
      .api(ServerApiEnum.LOGIN)
      .body(data)
      .then(res -> {
        currentLoginUser = new FastTalkUserModel();
        currentLoginUser.setUserName(data.getUserName());
      }).execute();
  }

  public static MessagesManagerClient getInstance() {
    return manage;
  }

  public void addTalkListener(Consumer<TTalkRecordInfo> consumer) {
    talkListenerList.add(consumer);
  }

  public List<FastTalkGroupModel> getFastTalkGroupList() {
    HttpResponse<String> response = HttpActuatorBuilder.builder()
      .serverUrl(data.getServerUrl())
      .api(ServerApiEnum.GET_GROUPS)
      .execute();
    return Constant.GSON.fromJson(response.body(), new TypeToken<List<FastTalkGroupModel>>() {}.getType());
  }

  public FastTalkUserModel getCurrentLoginUser() {
    return currentLoginUser;
  }

  public void sendTalkText(String sendText, FastTalkGroupModel fastTalkGroupModel) {
    TTalkRecordInfo recordInfo = new TTalkRecordInfo();
    recordInfo.setText(sendText);
    recordInfo.setName(currentLoginUser.getUserName());
    recordInfo.setDate(new Date());
    recordInfo.setGroupId(fastTalkGroupModel.getId());
    HttpActuatorBuilder.builder()
      .serverUrl(data.getServerUrl())
      .api(ServerApiEnum.SEND_TEXT)
      .body(recordInfo)
      .execute();
  }
}
